<template>
  <div style="height: 100%;background-color:white ;padding: 5px">
    <div>
      <div style="display: inline-block">
        <el-button icon="el-icon-back" type="text" @click="goBack">返回</el-button>
      </div>
      <div style="display: inline-block">|</div>
      <div style="display: inline-block;">
        <div style="padding-bottom: 15px;">
          <span style="font-family: 'Microsoft YaHei',sans-serif;display: inline-block">新建知识库</span>
        </div>
      </div>
      <div style="border-bottom: solid 1px #C9C9C9;"></div>
    </div>
    <div :style="contentStyle">
      <el-row>
        <el-col :span="24">
          <div style="margin-bottom: 10px;">
            <el-button class="button" size="small" type="primary" @click="confirm">提交</el-button>
            <el-button class="button" plain size="small" type="primary" @click="export1">导出</el-button>
<!--            <el-button class="button" plain size="small" type="primary" @click="download()">下载word模板</el-button>-->
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22">
          <label style="margin-right: 5px;"> 知识库名称:<span style="color: red">*</span></label>
          <el-input v-model="knowledgeName" placeholder="请输入知识库名称" size="small" style="width: 290px"></el-input>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px">
        <el-table highlight-current-row :data="tableData" border stripe style="width: 100%;">
          <el-table-column label="字段名称" min-width="200" prop="name">
            <template slot-scope="scope">
              <el-input v-model="scope.row.name"
                        :disabled="scope.$index === 0"
                        placeholder="请输出"
                        size="small"
                        @change="((value) => {selectName(value, scope.$index)})">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="字段类型" min-width="180" prop="type">
            <template slot-scope="scope">
              <el-select v-model="scope.row.kind"
                         :disabled="scope.$index === 0"
                         placeholder="请选择"
                         size="small"
                         @change="((value) => {selectType(value, scope.$index)})">
                <el-option
                  v-for="(item,index) in types"
                  :key="index"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="类型详情" min-width="150" prop="tag">
            <template slot-scope="scope">
              <el-link
                v-if="scope.row.kind === '3' || scope.row.kind === '5'"
                style="color: #2db7a0"
                @click="showDetail(scope.row.kind, scope.$index)">查看详情
              </el-link>
              <el-select v-else-if="scope.row.kind === '9'" filterable v-model="scope.row.kindValue">
                <el-option v-for="item in $store.state.knowledgeLibList" :key="item.id" :label="item.name"
                           :value="item.id"></el-option>
              </el-select>
              <div v-else>{{scope.row.fieldTypeDetail}}</div>
            </template>
          </el-table-column>
          <el-table-column label="是否必填" min-width="60" prop="required">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.required"
                         active-color="#2db7a0"
                         active-text="是"
                         active-value="true"
                         inactive-color="#c9c9c9"
                         inactive-text="否"
                         :disabled="scope.$index === 0"
                         inactive-value="false"/>
            </template>
          </el-table-column>
          <el-table-column label="排序" width="100">
            <template slot-scope="scope">
              <el-link v-if="scope.row.index !== 0"
                       :disabled="scope.$index === 1"
                       style="color: #2db7a0"
                       @click="moveUp(scope.$index)">上移
              </el-link>
              <el-link v-if="scope.row.index !== scope.row.endIndex"
                       :disabled="scope.$index === 0"
                       style="color: #2db7a0"
                       @click="moveDown(scope.$index)">下移
              </el-link>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="50">
            <template slot-scope="scope">
              <span><el-link :disabled="scope.$index === 0"
                             @click="deleteItem(scope.$index)">删除</el-link></span>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row>
        <div style="text-align: center; border: solid 1px #e6e9f3; height: 48px; line-height: 48px;">
          <el-link style="color: #2db7a0" @click="addClick"><i class="el-icon-plus"></i> 新增字段</el-link>
        </div>
      </el-row>
    </div>
    <el-dialog :visible="showTagSelectionDialog"
               title="设置字段类型"
               @close="showTagSelectionDialog = false"
               width="500px">
      <el-row>
        <el-col :offset="12" :span="12">
          <div style="margin-bottom: 10px;">
            <el-input v-model="queryString"
                      placeholder="请输入分类名称"
                      prefix-icon="el-icon-search"
                      size="small"
                      @change="updateTags(queryString)"></el-input>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div style="height: 200px; overflow: auto; ">
            <el-radio-group v-for="(tag, index) in tags" :key="index" v-model="selectedTag">
              <el-radio :label="tag.value" style="width: 150px;">{{tag.label}}</el-radio>
            </el-radio-group>
          </div>
        </el-col>
      </el-row>
      <span slot="footer" class="el-dialog__footer">
        <el-button size="small" @click="showTagSelectionDialog = false">取 消</el-button>
        <el-button size="small" type="primary" @click="handleTagSelection(selectedTag)">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible="showRadioDropBoxDialog"
               @close="showRadioDropBoxDialog = false"
               title="设置字段类型">
      <el-row>
        <el-col :span="12">
          <div style="display: inline-block; font-weight: bold; margin-right: 10px;">
            <div v-if="isSingleChoice">单选下拉框</div>
            <div v-else>多选下拉框</div>
          </div>
          <el-button plain size="small" type="primary"
                     @click="switchShowingAddNewOptionsDialog">
            <div v-if="showAddNewOptionsDialog"><i class="el-icon-back"></i> 选择字段</div>
            <div v-else><i class="el-icon-plus"></i> 新增选项</div>
          </el-button>
        </el-col>
        <el-col :span="12">
          <el-input v-model="radioName"
                    placeholder="搜索已有选项"
                    prefix-icon="el-icon-search"
                    size="small"
                    @change="updateRadioDropBoxDialog(radioName, 'single')">
          </el-input>
        </el-col>
      </el-row>
      <div style="height: 360px;overflow: auto; margin-top: 5px;">
        <el-row>
          <el-col :span="24">
            <div style="height: 1px; background-color: #C9C9C9; margin-top: 10px; margin-bottom: 10px;"></div>
          </el-col>
        </el-row>
        <el-row v-if="showAddNewOptionsDialog">
          <el-col :span="24">
            <el-row>
              <el-col :span="3">选项题干<span style="color: red">*</span></el-col>
              <el-col :span="21">
                <div style="margin-bottom: 10px;">
                  <el-input v-model="optionTitle" placeholder="请输入" size="small"></el-input>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="3">选项内容<span style="color: red">*</span></el-col>
              <el-col :span="21">
                <el-row v-for="(option, index) in options" :key="index">
                  <el-col :span="22">
                    <div style="margin-bottom: 10px; margin-right: 10px;">
                      <el-input v-model="option.name" placeholder="题目的具体描述" size="small"></el-input>
                    </div>
                  </el-col>
                  <el-col :span="2">
                    <div>
                      <el-button v-if="index === 0" circle icon="el-icon-plus" plain size="small" type="success"
                                 @click="addOption"></el-button>
                      <el-button v-else circle icon="el-icon-minus" plain size="small" type="danger"
                                 @click="deleteOption(index, option)"></el-button>
                    </div>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row v-else>
          <el-col :span="24">
            <SelectionList v-model="selectedRule"
                           :selections="selections"
                           @change="selectionListChange"
                           @edit="editOption"/>
          </el-col>
        </el-row>
      </div>
      <el-row style="text-align: right;height: 60px; line-height: 60px;">
        <el-col :span="24">
          <el-button size="small" @click="handleRadioCancel">取 消</el-button>
          <el-button size="small" type="primary" @click="handleRadioSelection(selectedRule)">确 定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import Label from "../calculator/exportModel/Label";
import SelectionList from "./SelectionList";

const inputBox = '0'                      // 输入框
const richText = '1'                      // 富文本
const reference = '2'                     // 参照
const radioDropDownBox = '3'              // 单选下拉框
const image = '4'                         // 图片
const multipleSelectionDropDownBox = '5'  // 多选下拉框
const textarea = '6'                      // 文本域
const multiValueInputBox = '7'            // 多值输入框
const associateCurrentKnowledgeLib = '8'  // 关联本知识库
const associateOtherKnowledgeLib = '9'    // 关联其他知识库
const associatePlatform = '10'            // 关联应用平台
const video = '11'                        // 视频
const file = '12'                         // 文件类型

export default {
  name: "new",
  components: {SelectionList, Label},
  data() {
    return {
      radioName: '',
      types: [],
      optionTitle: '',
      options: [],
      tags: [],
      knowledgeName: '',
      tableData: [],
      tableHeight: '',
      contentStyle: '',
      showTagSelectionDialog: false,
      showRadioDropBoxDialog: false,
      isSingleChoice: true,
      selectedTag: '',
      queryString: '',
      operatedIndex: 0,
      selections: [],
      selectedRule: '',
      showAddNewOptionsDialog: false,
      knowledgeLibId: '',
      waitingResponse: false,
      deletedOption: [],
      knowledgeCount: '',
    }
  },
  methods: {
    moveUp(index) {
      let tempTableData = this.tableData

      tempTableData[index].index--
      tempTableData[index - 1].index++

      let temp = {};
      temp = tempTableData[index]
      tempTableData[index] = tempTableData[index - 1]
      tempTableData[index - 1] = temp

      this.tableData = tempTableData
    },
    moveDown(index) {
      let tempTableData = this.tableData

      tempTableData[index].index++
      tempTableData[index + 1].index--

      let temp = {};
      temp = tempTableData[index]
      tempTableData[index] = tempTableData[index + 1]
      tempTableData[index + 1] = temp

      this.tableData = tempTableData
    },
    addOption() {
      let option = {
        id: "",
        value: this.options.length,
        name: ""
      }
      this.options.push(option)
    },
    deleteOption(index, option) {
      // 查询选项是否被其他知识引用，如果被引用则不允许删除
      this.axios.get("/pmph/action/knowledgeLib/selectBindingField", {
        params: {
          id: option.id,
          kindValue: option.kindValue,
          isSingle: this.isSingleChoice
        }
      }).then((res) => {
        let knowledgeArray = [{id: "", name: ""}]
        knowledgeArray = res.data;
        if (knowledgeArray.length > 0) {
          this.$message.error("选项被知识关联，不可删除")
        } else {
          this.options.splice(index, 1)
          for (let i = 0; i < this.options.length; i++) {
            this.options.value = i
          }
          this.deletedOption.push(option)
        }
      })
    },
    switchShowingAddNewOptionsDialog() {
      this.optionTitle = ""
      this.options = [{
        id: "",
        name: "",
        value: 0
      }]
      this.showAddNewOptionsDialog = !this.showAddNewOptionsDialog
    },
    showDetail(kind, index) {
      // 重置搜索条件
      this.radioName = ""
      this.operatedIndex = index

      if (kind === radioDropDownBox) {
        // 设置即将显示的对话框对应的rule id
        this.selectedRule = this.tableData[index].kindValue
        // 更新规则列表
        this.updateRadioDropBoxDialog("", "single")
        this.isSingleChoice = true
        // 显示对话框
        this.showRadioDropBoxDialog = true
      } else if (kind === multipleSelectionDropDownBox) {
        this.selectedRule = this.tableData[index].kindValue
        this.updateRadioDropBoxDialog("", "multi")
        this.isSingleChoice = false
        this.showRadioDropBoxDialog = true
      }
    },
    selectionListChange() {
      console.log("selectionListChange call: " + this.selectedRule);
    },
    addClick() {
      let tableDataItem = {
        name: '',
        kind: '',
        kindValue: '',
        required: '',
        fieldTypeDetail: '',
        index: 0,
        endIndex: 0
      }
      tableDataItem.index = this.tableData.length
      this.tableData.push(tableDataItem)
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].endIndex = this.tableData.length - 1
      }
      this.showSubject()
    },
    //删除按钮点击事件
    deleteItem(index) {
      this.$confirm('您确认要删除此字段？删除该库所有知识的该字段将被一并删除，涉及知识条数为' + this.knowledgeCount + '条', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.tableData.splice(index, 1)
      })
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].index = i
        this.tableData[i].endIndex = this.tableData.length - 1
      }
    },
    // 分类交换事件，并校验
    selectType(value, index) {
      this.tableData[index].kind = value
      this.tableData[index].fieldTypeDetail = ''
      this.operatedIndex = index

      if (value === reference) {
        this.axios.get("/pmph/action/knowledgeLib/selectTagData").then((response) => {
          this.tags = response.data
          this.showTagSelectionDialog = true
        }).catch((error) => {
          console.error(error)
          this.$message.error("获取分类数据失败")
        })
      } else if (value === radioDropDownBox) {
        this.axios.get("/pmph/action/knowledgeLib/selectRuleData", {
          params: {
            ruleName: "",
            type: "single"
          }
        }).then((response) => {
          // 重置搜索条件
          this.radioName = ""
          // 重置选择结果
          this.selectedRule = ""
          // 更新数据
          this.selections = response.data
          // 设置单选标志
          this.isSingleChoice = true
          // 显示对话框
          this.showRadioDropBoxDialog = true
        }).catch((error) => {
          console.error(error)
          this.$message.error("获取选项数据失败")
        })
      } else if (value === multipleSelectionDropDownBox) {
        this.axios.get("/pmph/action/knowledgeLib/selectRuleData", {
          params: {
            ruleName: "",
            type: "multi"
          }
        }).then((response) => {
          // 重置搜索条件
          this.radioName = ""
          // 重置选择结果
          this.selectedRule = ""
          // 更新数据
          this.selections = response.data
          // 设置单选标志
          this.isSingleChoice = false
          // 显示对话框
          this.showRadioDropBoxDialog = true
        }).catch((error) => {
          console.error(error)
          this.$message.error("获取选项数据失败")
        })
      } else if (value === associateOtherKnowledgeLib) {
      }
    },
    updateTags(queryString) {
      this.axios.get("/pmph/action/knowledgeLib/selectTagData", {
        params: {
          queryString: queryString
        }
      }).then((response) => {
        this.tags = response.data
      }).catch((error) => {
        console.error(error)
        this.$message.error("获取分类数据失败")
      })
    },
    download() {
      window.location.href = "/pmph/action/knowledgeLib/downloadZip?knowledgeLibId=" + this.knowledgeLibId
    },
    selectOption(value, index) {
      this.tableData[index].kindValue = value
    },
    selectRequired(value, index) {
      this.tableData[index].required = value
    },
    selectName(value, index) {
      this.tableData[index].name = value
      for (let i = 0; i < this.tableData.length; i++) {
        if (i !== index) {
          if (this.tableData[i].name === this.tableData[index].name) {
            this.$message.warning("名称重复请重新填写")
            this.tableData[index].name = '';
            return;
          }
        }
      }
    },
    //取消按钮
    cancel() {
      this.$router.push("/KnowledgeLib")
    },
    showSubject: function () {
      // 获取关联分类数据
      this.axios.get("/pmph/action/knowledgeLib/selectTagData", {})
        .then((response) => {
          this.tags = response.data
        })
        .catch((error) => {
          console.error(error)
          this.$message.error("获取分类数据失败")
        })
    },
    //返回按钮点击事件
    goBack: function () {
      this.$router.push("/KnowledgeLib")
    },
    //确定按钮点击事件
    confirm: function () {
      if (this.waitingResponse) {
        return
      }
      this.waitingResponse = true

      if (this.knowledgeName === '' || this.knowledgeName === null) {
        console.log(this.tableData)
        this.$message.warning("请填写知识库名称")
        this.waitingResponse = false
        return;
      }

      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].name === '' || this.tableData[i].name === null) {
          this.$message.warning("请填写名称")
          this.waitingResponse = false
          return;
        }
        if (this.tableData[i].kind === '2') {
          if (this.tableData[i].kindValue === '') {
            this.$message.warning("请填写分类类型对应的关联分类")
            this.waitingResponse = false
            return;
          }
        }
        if (this.tableData[i].kind === '3' || this.tableData[i].kind === '5') {
          if (this.tableData[i].kindValue === '') {
            this.$message.warning("请填写对应的选项")
            this.waitingResponse = false
            return;
          }
        }
        if (this.tableData[i].kind === '9' && UTIL.isEmpty(this.tableData[i].kindValue)) {
            this.$message.warning("请指定关联其它知识库")
            this.waitingResponse = false
            return;
          }
        }

      // 检查字段类型是否都填写了
      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].kind === "") {
          this.$message.warning("必须填写字段类型")
          this.waitingResponse = false
          return
        }
      }

      // 检查知识库名称是否重复
      this.axios.get("/pmph/action/knowledgeLib/selectCheckRepeatName", {
        async: false,
        params: {
          name: this.knowledgeName
        }
      }).then((res) => {
        let isRepeatName = res.data
        if (this.$route.query.id) {

        } else {
          if (isRepeatName === true) {
            this.$message.warning("知识库名称重复")
            this.waitingResponse = false
            return
          }
        }

        let param = new URLSearchParams();
        param.append("knowledgeName", this.knowledgeName)
        param.append("tableData", JSON.stringify(this.tableData))
        if (this.$route.query.id) {
          param.append("id", this.knowledgeLibId)
          this.axios.post('/pmph/action/knowledgeLib/editAdd', param)
            .then((response) => {
              if (response.data === true) {
                this.$router.push("/KnowledgeLib")
              } else {
                this.waitingResponse = false
              }
            })
            .catch((error) => {
              this.waitingResponse = false
            })
        } else {
          param.append("specialtyId", this.$route.query.specialtyId)
          this.axios.post('/pmph/action/knowledgeLib/newAdd', param)
            .then((response) => {
                this.$router.push({
                  path: '/knowledgeLib',
                  query: {
                    knowledgeLibIdList: JSON.stringify(response.data.knowledgeLibIdList)
                  }
                })
            })
            .catch((error) => {
              this.waitingResponse = false
              console.error(error)
            })
        }
      }).catch((err) => {
        console.error(err);
        this.$message.error("验证知识库名称失败，知识库保存失败")
        this.waitingResponse = false
      })
    },
    //导出按钮点击事件
    export1: function () {
      window.location.href = '/pmph/action/knowledgeLib/export?knowledgeLibId=' + this.knowledgeLibId + '&knowledgeName=' + this.knowledgeName
    },
    handleTagSelection(selectedTag) {
      this.tableData[this.operatedIndex].kindValue = selectedTag

      for (let i = 0; i < this.tags.length; i++) {
        if (this.tags[i].value === selectedTag) {
          this.tableData[this.operatedIndex].fieldTypeDetail = this.tags[i].label
          break
        }
      }
      this.showTagSelectionDialog = false
    },
    handleRadioCancel() {
      if (this.showAddNewOptionsDialog) {
        this.showAddNewOptionsDialog = false
      } else {
        this.showRadioDropBoxDialog = false
      }
    },
    handleRadioSelection(selectedRadio) {
      if (this.showAddNewOptionsDialog) {
        if (this.optionTitle === "") {
          this.$message.warning("必须填写选项题干")
          return
        } else if (this.options[0].name === "") {
          this.$message.warning("至少有一个选项")
          return
        }

        let optionType = ""
        if (this.tableData[this.operatedIndex].kind === "3") {
          optionType = "single"
        } else if (this.tableData[this.operatedIndex].kind === "5") {
          optionType = "multi"
        }
        this.axios.get("/pmph/action/knowledgeLib/addRule", {
          params: {
            ruleName: this.optionTitle,
            ruleType: optionType,
            ruleItems: JSON.stringify(this.options),
            deletedOptions: JSON.stringify(this.deletedOption)
          }
        }).then((res) => {

            if (optionType === "single") {
              this.updateRadioDropBoxDialog("", "single")
            } else if (optionType === "multi") {
              this.updateRadioDropBoxDialog("", "multi")
            }

          this.showAddNewOptionsDialog = false
        }).catch((err) => {
          console.error(err)
        })
      } else {
        this.tableData[this.operatedIndex].kindValue = selectedRadio
        this.showRadioDropBoxDialog = false
      }
    },
    updateRadioDropBoxDialog(ruleName, type) {
      this.axios.get("/pmph/action/knowledgeLib/selectRuleData", {
        params: {
          ruleName: ruleName,
          type: type
        }
      }).then((response) => {
        this.selections = response.data
      }).catch((error) => {
        console.error(error)
        this.$message.error("获取选项数据失败")
      })
    },
    handleKLibSelectionCancel() {
      let knowledgeLibId = this.tableData[this.operatedIndex].kindValue
      if (knowledgeLibId === undefined || knowledgeLibId === "") {
        this.$message.error("必须选择一个知识库")
        // 如果没有选择知识库，则把个字段的类型恢复到初始状态
        let tableDataItem = {
          name: '',
          kind: '',
          kindValue: '',
          required: '',
          fieldTypeDetail: '',
          index: 0,
          endIndex: 0
        }
        this.tableData.splice(this.operatedIndex, 1, tableDataItem)
      }
    },
    editOption(selection) {
      this.optionTitle = selection.title
      this.options = selection.options
      this.showAddNewOptionsDialog = true
    }
  },
  created() {
    this.contentStyle = "margin-top: 10px; height: " + (CONST.WORKSPACE_HEIGHT - 80) + "px; overflow: auto;"
    this.types = [{
      value: inputBox,
      label: '输入框'
    }, {
      value: richText,
      label: '富文本'
    }, {
      value: reference,
      label: '分类'
    }, {
      value: radioDropDownBox,
      label: '单选下拉框'
    }, {
      value: image,
      label: '图片'
    }, {
      value: multipleSelectionDropDownBox,
      label: '多选下拉框'
    }, {
      value: textarea,
      label: '文本域'
    }, {
      value: multiValueInputBox,
      label: '多值输入框'
    }, {
      value: associateCurrentKnowledgeLib,
      label: '关联本知识库'
    }, {
      value: associateOtherKnowledgeLib,
      label: '关联其他知识库'
    }, {
      value: associatePlatform,
      label: '关联应用平台'
    }, {
      value: video,
      label: '视频'
    }, {
      value: file,
      label: '文件'
    }]

    if (this.$route.query.id == null) {
      this.tableData = [{
        id: '',
        name: '名称',
        kind: '0',
        kindValue: '',
        required: 'true',
        fieldTypeDetail: '',
        index: 0,
        endIndex: 0
      }]
    } else {
      this.knowledgeLibId = this.$route.query.id
      this.knowledgeName = this.$route.query.name
      this.axios.get('/pmph/action/knowledgeLib/selectTableData', {
        params: {
          id: this.knowledgeLibId
        }
      }).then((response) => {
        let tempData = response.data.tableData
        for (let i = 0; i < tempData.length; i++) {
          tempData[i].index = i
        }
        this.tableData = tempData
        console.log(this.tableData)
        this.knowledgeCount = response.data.knowledgeCount

      })
    }
  },
  beforeDestroy() {
    this.waitingResponse = false
  },
  beforeRouteLeave(from, to, next) {
    if (to.name === "KnowledgeLib") {
      to.meta.isUseCache = false
    }
    next()
  }
}
</script>

<style scoped>
.button {
  width: 88px;
}

.el-select {
  width: 100%;
}

.el-select .el-input__inner {
  width: 100%;
}

.el-select .el-input.is-disabled .el-input__inner {
  cursor: not-allowed;
  width: 100%;
}

/deep/ .el-dialog__body {
  padding: 30px 20px 0 20px;
}
</style>
